package com.jhgsys.internal.hazard.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.accident.entity.HazardExamineAuditRecord;
import com.jhgsys.internal.accident.entity.HazardExamineFile;
import com.jhgsys.internal.accident.entity.HazardExamineRectificationReturnRecord;
import com.jhgsys.internal.accident.service.IHazardExamineAuditRecordService;
import com.jhgsys.internal.accident.service.IHazardExamineFileService;
import com.jhgsys.internal.accident.service.IHazardExamineRectificationReturnRecordService;
import com.jhgsys.internal.base.entity.BaseProject;
import com.jhgsys.internal.base.entity.BaseProjectArea;
import com.jhgsys.internal.base.entity.HazardExamineUser;
import com.jhgsys.internal.base.service.IBaseProjectAreaService;
import com.jhgsys.internal.base.service.IBaseProjectService;
import com.jhgsys.internal.base.service.IHazardExamineUserService;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.hazard.dto.HazardExamineDto;
import com.jhgsys.internal.hazard.dto.HazardExamineObjectDto;
import com.jhgsys.internal.hazard.dto.HazardExamineRecordDto;
import com.jhgsys.internal.hazard.dto.HazardExamineTeamDto;
import com.jhgsys.internal.hazard.entity.HazardExamine;
import com.jhgsys.internal.hazard.entity.HazardExamineObject;
import com.jhgsys.internal.hazard.entity.HazardExamineRecord;
import com.jhgsys.internal.hazard.entity.HazardExamineTeamUser;
import com.jhgsys.internal.hazard.service.IHazardExamineObjectService;
import com.jhgsys.internal.hazard.service.IHazardExamineRecordService;
import com.jhgsys.internal.hazard.service.IHazardExamineService;
import com.jhgsys.internal.system.entity.Dept;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IDeptService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 *  Controller
 *
 * @author admin
 * @date 2024-08-20 15:49:12
 */
@Slf4j
@Validated
@Controller
public class HazardExamineRecordController extends BaseController {

    @Autowired
    private IHazardExamineRecordService hazardExamineRecordService;

    @Autowired
    private IHazardExamineService hazardExamineService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IBaseProjectService baseProjectService;

    @Autowired
    private IBaseProjectAreaService baseProjectAreaService;

    @Autowired
    private IHazardExamineObjectService hazardExamineObjectService;

    @Autowired
    private IHazardExamineUserService hazardExamineUserService;

    @Autowired
    private IHazardExamineFileService hazardExamineFileService;

    @Autowired
    private IHazardExamineAuditRecordService hazardExamineAuditRecordService;

    @Autowired
    private IHazardExamineRectificationReturnRecordService hazardExamineRectificationReturnRecordService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineRecord")
    @RequiresPermissions("hazardExamineRecord:view")
    public String hazardExamineRecordIndex(Model model){
        setModelAttribute(model);
        return FebsUtil.view("hazard/hazardExamineRecord/hazardExamineRecordList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineRectify")
    @RequiresPermissions("hazardExamineRectify:view")
    public String hazardExamineRectifyIndex(Model model){
        setModelAttribute(model);
        return FebsUtil.view("hazard/hazardExamineRectify/hazardExamineRectifyList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineAudit")
    @RequiresPermissions("hazardExamineAudit:view")
    public String hazardExamineAuditIndex(Model model){
        setModelAttribute(model);
        return FebsUtil.view("hazard/hazardExamineAudit/hazardExamineAuditList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineRecord/add/{examineId}/{examineObjectId}")
    @RequiresPermissions("hazardExamineRecord:add")
    public String hazardExamineRecordAdd(Model model, @PathVariable("examineId") String examineId, @PathVariable("examineObjectId") String examineObjectId) throws JsonProcessingException {
        HazardExamineRecordDto hazardExamineRecordDto = new HazardExamineRecordDto();
        hazardExamineRecordDto.setExamineId(examineId);
        setTeamUserList(hazardExamineRecordDto,examineObjectId);
        model.addAttribute("hazardExamineRecord",hazardExamineRecordDto);

        HazardExamineDto hazardExamineDto = hazardExamineService.findHazardExamineById(examineId);
        model.addAttribute("hazardExamine", JSON.parse(new ObjectMapper().writeValueAsString(hazardExamineDto)));

        //项目
        model.addAttribute("projectList",setModelProject(hazardExamineDto));

        setModelAttribute(model);
        return FebsUtil.view("hazard/hazardExamineRecord/hazardExamineRecordEdit");
    }

    private void setTeamUserList(HazardExamineRecordDto hazardExamineRecordDto,String examineObjectId){
        //当前检查项的检查组人员
        List<HazardExamineUser> hazardExamineUserList = hazardExamineUserService.list(new LambdaQueryWrapper<HazardExamineUser>()
                .eq(HazardExamineUser::getExamineObjectId, examineObjectId)
                .eq(HazardExamineUser::getDeletedFlg, FebsConstant.VALID));
        //根据groupName对HazardExamineUser进行分组
        Map<String,List<HazardExamineUser>> map = hazardExamineUserList.stream().collect(Collectors.groupingBy(HazardExamineUser::getGroupName));
        List<HazardExamineTeamDto> teamList = new ArrayList<>();
        map.forEach((k,v) ->{
            HazardExamineTeamDto hazardExamineTeamDto = new HazardExamineTeamDto();
            hazardExamineTeamDto.setTeamName(k);
            List<HazardExamineTeamUser> hazardExamineTeamUserList = v.stream().map(b ->{
                HazardExamineTeamUser hazardExamineTeamUser = BeanHelper.copyProperties(b,HazardExamineTeamUser.class);
                hazardExamineTeamUser.setUserDeptId(b.getDeptId());
                hazardExamineTeamUser.setUserDeptName(b.getDeptName());
                return hazardExamineTeamUser;
            }).collect(Collectors.toList());
            hazardExamineTeamDto.setTeamUserList(hazardExamineTeamUserList);
            teamList.add(hazardExamineTeamDto);
        });
        hazardExamineRecordDto.setTeamUserList(teamList);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineRecord/update/{examineId}/{examineRecordId}/{examineObjectId}")
    @RequiresPermissions("hazardExamineRecord:edit")
    public String hazardExamineRecordUpdate(Model model, @PathVariable("examineId") String examineId,
                                                        @PathVariable("examineRecordId") String examineRecordId,
                                                        @PathVariable("examineObjectId") String examineObjectId) throws JsonProcessingException{
        setModelAttribute(model);

        HazardExamineDto hazardExamineDto = hazardExamineService.findHazardExamineById(examineId);
        model.addAttribute("hazardExamine", JSON.parse(new ObjectMapper().writeValueAsString(hazardExamineDto)));

        HazardExamineRecordDto hazardExamineRecordDto = hazardExamineRecordService.findHazardExamineRecordById(examineRecordId);
        setTeamUserList(hazardExamineRecordDto,examineObjectId);
        model.addAttribute("hazardExamineRecord", JSON.parse(new ObjectMapper().writeValueAsString(hazardExamineRecordDto)));

        //项目
        model.addAttribute("projectList",setModelProject(hazardExamineDto));
        return FebsUtil.view("hazard/hazardExamineRecord/hazardExamineRecordEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineRectify/rectify/{examineId}/{examineRecordId}")
    @RequiresPermissions("hazardExamineRectify:rectify")
    public String hazardExamineRectify(Model model, @PathVariable("examineId") String examineId, @PathVariable("examineRecordId") String examineRecordId) throws JsonProcessingException{
        setModelAttribute(model);
        HazardExamineDto hazardExamineDto = hazardExamineService.findHazardExamineById(examineId);
        model.addAttribute("hazardExamine", JSON.parse(new ObjectMapper().writeValueAsString(hazardExamineDto)));
        HazardExamineRecordDto hazardExamineRecordDto = hazardExamineRecordService.findHazardExamineRecordById(examineRecordId);
        model.addAttribute("hazardExamineRectify", JSON.parse(new ObjectMapper().writeValueAsString(hazardExamineRecordDto)));
        return FebsUtil.view("hazard/hazardExamineRectify/hazardExamineRectifyEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineAudit/audit/{examineId}/{examineRecordId}")
    @RequiresPermissions("hazardExamineAudit:audit")
    public String hazardExamineAudit(Model model, @PathVariable("examineId") String examineId, @PathVariable("examineRecordId") String examineRecordId) throws JsonProcessingException{
        setModelAttribute(model);
        HazardExamineDto hazardExamineDto = hazardExamineService.findHazardExamineById(examineId);
        model.addAttribute("hazardExamine", JSON.parse(new ObjectMapper().writeValueAsString(hazardExamineDto)));
        HazardExamineRecordDto hazardExamineRecordDto = hazardExamineRecordService.findHazardExamineRecordById(examineRecordId);
        model.addAttribute("hazardExamineAudit", JSON.parse(new ObjectMapper().writeValueAsString(hazardExamineRecordDto)));
        return FebsUtil.view("hazard/hazardExamineAudit/hazardExamineAuditEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineDetail/detail/{examineId}/{examineRecordId}")
    @RequiresPermissions("hazardExamineRecord:view")
    public String hazardExamineDetail(Model model, @PathVariable("examineId") String examineId, @PathVariable("examineRecordId") String examineRecordId) throws JsonProcessingException{
        setModelAttribute(model);
        HazardExamineDto hazardExamineDto = hazardExamineService.findHazardExamineById(examineId);
        model.addAttribute("hazardExamine", JSON.parse(new ObjectMapper().writeValueAsString(hazardExamineDto)));
        HazardExamineRecordDto hazardExamineRecordDto = hazardExamineRecordService.findHazardExamineRecordById(examineRecordId);
        model.addAttribute("hazardExamineDetail", JSON.parse(new ObjectMapper().writeValueAsString(hazardExamineRecordDto)));
        return FebsUtil.view("hazard/hazardExamine/hazardExamineDetail");
    }

    /**
     * 查询（所有）
     * @author admin
     * @date 2024-08-20 15:49:12
     */
    @GetMapping("hazardExamineRecord")
    @ResponseBody
    @RequiresPermissions("hazardExamineRecord:view")
    public FebsResponse getAllHazardExamineRecords(HazardExamineRecord hazardExamineRecord) {
        return new FebsResponse().success().data(hazardExamineRecordService.findHazardExamineRecordList(hazardExamineRecord));
    }

    /**
     * 安全检查录入 以HazardExamine为主表查询（所有）
     * @author admin
     * @date 2024-08-20 15:49:12
     */
    @GetMapping("hazardExamineRecordList")
    @ResponseBody
    @RequiresPermissions("hazardExamineRecord:view")
    public FebsResponse findHazardExamineRecordListWithExamines(HazardExamineRecordDto hazardExamineRecordDto) {
        if(null == hazardExamineRecordDto.getTenantId()){
            hazardExamineRecordDto.setTenantId(getCurrentTenantId());
        }
        hazardExamineRecordDto.setUserId(getCurrentUser().getUserId());
        return new FebsResponse().success().data(hazardExamineRecordService.findHazardExamineRecordListWithExamines(hazardExamineRecordDto));
    }

    /**
     * 查询（分页）
     * @author admin
     * @date 2024-08-20 15:49:12
     */
    @GetMapping("hazardExamineRecord/list")
    @ResponseBody
    @RequiresPermissions("hazardExamineRecord:view")
    public FebsResponse hazardExamineRecordList(QueryRequest request, HazardExamineRecord hazardExamineRecord) {
        Map<String, Object> dataTable = getDataTable(this.hazardExamineRecordService.findHazardExamineRecordPage(request, hazardExamineRecord));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 HazardExamineRecord
     * @author admin
     * @date 2024-08-20 15:49:12
     */
    @Log("新增HazardExamineRecord")
    @PostMapping("hazardExamineRecord")
    @ResponseBody
    @RequiresPermissions("hazardExamineRecord:add")
    public FebsResponse addHazardExamineRecord(@RequestBody HazardExamineRecordDto hazardExamineRecordDto) throws FebsException {
        try {
            HazardExamineRecord hazardExamineRecord = BeanHelper.copyProperties(hazardExamineRecordDto,HazardExamineRecord.class);
            User user = getCurrentUser();
            hazardExamineRecord.setCreatedBy(user.getUserName());
            hazardExamineRecord.setRecordDate(new Date());
            hazardExamineRecord.setRecordUserId(user.getUserId());
            hazardExamineRecord.setRecordRealName(user.getUname());
            this.hazardExamineRecordService.createHazardExamineRecord(hazardExamineRecord);
            hazardExamineRecordDto.setExamineRecordId(hazardExamineRecord.getExamineRecordId());
            //保存问题附件
            if(CollectionUtils.isNotEmpty(hazardExamineRecordDto.getExamineFileList())){
                hazardExamineRecordDto.setFileType("1");
                saveExamineFile(hazardExamineRecordDto,hazardExamineRecordDto.getExamineFileList());
            }
            //修改安全检查发布状态
            HazardExamine hazardExamine = new HazardExamine();
            hazardExamine.setExamineId(hazardExamineRecordDto.getExamineId());
            hazardExamine.setStatus(hazardExamineRecordDto.getExamineStatus());
            hazardExamineService.updateById(hazardExamine);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增HazardExamineRecord失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 逻辑删除 HazardExamineRecord
     * @author admin
     * @date 2024-08-20 15:49:12
     */
    @Log("逻辑删除HazardExamineRecord")
    @GetMapping("hazardExamineRecord/delete/{id}")
    @ResponseBody
    @RequiresPermissions("hazardExamineRecord:delete")
    public FebsResponse deleteHazardExamineRecord(@PathVariable("id") String hazardExamineRecordIds) throws FebsException {
        try {
            HazardExamineRecord hazardExamineRecord = new HazardExamineRecord();
            hazardExamineRecord.setDeletedBy(getCurrentUser().getUserName());
            hazardExamineRecord.setDeletedTime(new Date());
            hazardExamineRecord.setDeletedFlg(FebsConstant.INVALID);
            this.hazardExamineRecordService.deleteHazardExamineRecord(hazardExamineRecord,hazardExamineRecordIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除HazardExamineRecord失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
    * 物理删除 HazardExamineRecord
    * @author admin
    * @date 2024-08-20 15:49:12
    */
    @Log("物理删除HazardExamineRecord")
    @GetMapping("hazardExamineRecord/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("hazardExamineRecord:delete")
    public FebsResponse physicallyDeleteHazardExamineRecord(@PathVariable("id") String hazardExamineRecordIds) throws FebsException {
        try {
            this.hazardExamineRecordService.physicallyDeleteHazardExamineRecord(hazardExamineRecordIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除HazardExamineRecord失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 修改 HazardExamineRecord
     * @author admin
     * @date 2024-08-20 15:49:12
     */
    @Log("修改HazardExamineRecord")
    @PostMapping("hazardExamineRecord/update")
    @ResponseBody
    @RequiresPermissions("hazardExamineRecord:edit")
    public FebsResponse updateHazardExamineRecord(@RequestBody HazardExamineRecordDto hazardExamineRecordDto) throws FebsException {
        if(hazardExamineService.ifClosed(hazardExamineRecordDto.getExamineId())){
            throw new FebsException("安全检查已结束！");
        }
        try {
            HazardExamineRecord hazardExamineRecord = BeanHelper.copyProperties(hazardExamineRecordDto,HazardExamineRecord.class);
            hazardExamineRecord.setUpdatedBy(getCurrentUser().getUserName());
            this.hazardExamineRecordService.updateHazardExamineRecord(hazardExamineRecord);
            //保存问题附件
            if(CollectionUtils.isNotEmpty(hazardExamineRecordDto.getExamineFileList())){
                hazardExamineRecordDto.setFileType("1");
                saveExamineFile(hazardExamineRecordDto,hazardExamineRecordDto.getExamineFileList());
            }
            //修改安全检查发布状态
            HazardExamine hazardExamine = new HazardExamine();
            hazardExamine.setExamineId(hazardExamineRecordDto.getExamineId());
            hazardExamine.setStatus(hazardExamineRecordDto.getExamineStatus());
            hazardExamineService.updateById(hazardExamine);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改HazardExamineRecord失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 整改 HazardExamineRecord
     * @author admin
     * @date 2024-08-20 15:49:12
     */
    @Log("整改HazardExamineRecord")
    @PostMapping("hazardExamineRectify/rectify")
    @ResponseBody
    @RequiresPermissions("hazardExamineRectify:rectify")
    public FebsResponse updateHazardExamineRectify(@RequestBody HazardExamineRecordDto hazardExamineRecordDto) throws FebsException {
        if(hazardExamineService.ifClosed(hazardExamineRecordDto.getExamineId())){
            throw new FebsException("安全检查已结束！");
        }
        try {
            HazardExamineRecord hazardExamineRecord = BeanHelper.copyProperties(hazardExamineRecordDto,HazardExamineRecord.class);
            hazardExamineRecord.setFeedbackDate(new Date());
            this.hazardExamineRecordService.updateHazardExamineRecord(hazardExamineRecord);
            //保存整改附件
            if(CollectionUtils.isNotEmpty(hazardExamineRecordDto.getRectifyFileList())){
                hazardExamineRecordDto.setFileType("2");
                saveExamineFile(hazardExamineRecordDto,hazardExamineRecordDto.getRectifyFileList());
            }
            //保存整改退回记录
            if("2".equals(hazardExamineRecordDto.getRectifyResult())){
                saveRectifyReturnRecord(hazardExamineRecordDto);
            }
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "整改信息录入失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 审核 HazardExamineRecord
     * @author admin
     * @date 2024-08-20 15:49:12
     */
    @Log("审核HazardExamineRecord")
    @PostMapping("hazardExamineAudit/audit")
    @ResponseBody
    @RequiresPermissions("hazardExamineAudit:audit")
    public FebsResponse updateHazardExamineAudit(@RequestBody HazardExamineRecordDto hazardExamineRecordDto) throws FebsException {
        if(hazardExamineService.ifClosed(hazardExamineRecordDto.getExamineId())){
            throw new FebsException("安全检查已结束！");
        }
        try {
            User user = getCurrentUser();
            HazardExamineRecord hazardExamineRecord = BeanHelper.copyProperties(hazardExamineRecordDto,HazardExamineRecord.class);
            hazardExamineRecord.setAuditDate(new Date());
            hazardExamineRecord.setAuditUserId(user.getUserId());
            hazardExamineRecord.setAuditRealName(user.getUname());
            this.hazardExamineRecordService.updateHazardExamineRecord(hazardExamineRecord);
            //保存审核记录
            saveAuditRecord(hazardExamineRecordDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "整改信息审核失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 导出 HazardExamineRecord的excel
     * @author admin
     * @date 2024-08-20 15:49:12
     */
    @PostMapping("hazardExamineRecord/excel")
    @ResponseBody
    @RequiresPermissions("hazardExamineRecord:view")
    public void export(QueryRequest queryRequest, HazardExamineRecord hazardExamineRecord, HttpServletResponse response) throws FebsException {
        try {
            List<HazardExamineRecord> hazardExamineRecords = this.hazardExamineRecordService.findHazardExamineRecordPage(queryRequest, hazardExamineRecord).getRecords();
            ExcelKit.$Export(HazardExamineRecord.class, response).downXlsx(hazardExamineRecords, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    private void setModelAttribute(Model model){
        model.addAttribute("currentUser",getCurrentUser());
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        //部门
        List<Dept> deptList = deptService.list(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getTenantId,getCurrentTenantId())
                .eq(Dept::getDeletedFlg,FebsConstant.VALID));
        model.addAttribute("deptList",deptList);
    }

    private List<BaseProjectArea> setModelArea(HazardExamineDto hazardExamineDto){
        //区域
        List<BaseProjectArea> areaList = new ArrayList<>();
        //如果是项目检查，则查询所选项目下的区域
        if("6".equals(hazardExamineDto.getExamineType())){
            List<HazardExamineObjectDto> hazardExamineObjectDtos = hazardExamineObjectService.findByExamineIds(Arrays.asList(hazardExamineDto.getExamineId()));
            if(CollectionUtils.isNotEmpty(hazardExamineObjectDtos)){
                List<String> projectIds = hazardExamineObjectDtos.stream().map(HazardExamineObjectDto::getObjectId).distinct().collect(Collectors.toList());
                areaList = baseProjectAreaService.findByProjectIds(projectIds);
            }
        }else{
            //查询公司下的所有区域
            BaseProjectArea baseProjectArea = new BaseProjectArea();
            baseProjectArea.setTenantId(getCurrentTenantId());
            areaList= baseProjectAreaService.findBaseProjectAreas(baseProjectArea);
        }
        return areaList;
    }

    private List<BaseProject> setModelProject(HazardExamineDto hazardExamineDto){
        //项目
        List<BaseProject> projectList = new ArrayList<>();
        //如果是项目检查，则查询安全发布时所选项目
        if("5".equals(hazardExamineDto.getExamineType())){
            List<HazardExamineObjectDto> hazardExamineObjectDtos = hazardExamineObjectService.findByExamineIds(Arrays.asList(hazardExamineDto.getExamineId()));
            if(CollectionUtils.isNotEmpty(hazardExamineObjectDtos)){
                List<String> projectIds = hazardExamineObjectDtos.stream().map(HazardExamineObjectDto::getObjectId).distinct().collect(Collectors.toList());
                projectList = baseProjectService.findBaseProjectsByIds(projectIds);
            }
        }else{
            //查询公司下的所有区域
            BaseProject baseProject = new BaseProject();
            baseProject.setTenantId(getCurrentTenantId());
            baseProject.setStatus("1");
            projectList= baseProjectService.findBaseProjects(baseProject);
        }
        return projectList;
    }

    /**
     * 保存检查记录问题附件
     * @author admin
     * @date 2024-08-22 14:19:15
     * @param hazardExamineRecordDto hazardExamineRecordDto
     * @param fileList fileList
     */
    private void saveExamineFile(HazardExamineRecordDto hazardExamineRecordDto,List<HazardExamineFile> fileList){
        //先删除，再保存
        hazardExamineFileService.deleteByExamineRecordIds(hazardExamineRecordDto.getExamineRecordId(),hazardExamineRecordDto.getFileType());
        if(CollectionUtils.isNotEmpty(fileList)){
            List<HazardExamineFile> accidentReportFileList = fileList.stream()
                    .map(d -> {
                        HazardExamineFile hazardExamineFile = BeanHelper.copyProperties(d,HazardExamineFile.class);
                        hazardExamineFile.setExamineId(hazardExamineRecordDto.getExamineId());
                        hazardExamineFile.setExamineRecordId(hazardExamineRecordDto.getExamineRecordId());
                        hazardExamineFile.setTenantId(hazardExamineRecordDto.getTenantId());
                        hazardExamineFile.setExamineFileType(hazardExamineRecordDto.getFileType());
                        hazardExamineFile.setCreatedTime(new Date());
                        hazardExamineFile.setCreatedBy(getCurrentUser().getUserId());
                        return hazardExamineFile;
                    }).collect(Collectors.toList());
            hazardExamineFileService.saveBatch(accidentReportFileList);
        }
    }

    /**
     * 保存检查记录审核记录
     * @author admin
     * @date 2024-08-23 10:19:15
     * @param hazardExamineRecordDto hazardExamineRecordDto
     */
    private void saveAuditRecord(HazardExamineRecordDto hazardExamineRecordDto){
        User user = getCurrentUser();
        if(null != hazardExamineRecordDto){
            HazardExamineAuditRecord hazardExamineAuditRecord = new HazardExamineAuditRecord();
            hazardExamineAuditRecord.setAuditResult(hazardExamineRecordDto.getAuditResult());
            hazardExamineAuditRecord.setAuditReason(hazardExamineRecordDto.getAuditRemark());
            hazardExamineAuditRecord.setAuditUserId(user.getUserId());
            hazardExamineAuditRecord.setAuditRealName(user.getUname());
            hazardExamineAuditRecord.setTenantId(hazardExamineRecordDto.getTenantId());
            hazardExamineAuditRecord.setExamineId(hazardExamineRecordDto.getExamineId());
            hazardExamineAuditRecord.setExamineRecordId(hazardExamineRecordDto.getExamineRecordId());
            hazardExamineAuditRecord.setCreatedTime(new Date());
            hazardExamineAuditRecordService.createHazardExamineAuditRecord(hazardExamineAuditRecord);
        }
    }

    /**
     * 保存整改反馈记录
     * @author admin
     * @date 2024-08-23 10:19:15
     * @param hazardExamineRecordDto hazardExamineRecordDto
     */
    private void saveRectifyReturnRecord(HazardExamineRecordDto hazardExamineRecordDto){
        User user = getCurrentUser();
        if(null != hazardExamineRecordDto){
            HazardExamineRectificationReturnRecord returnRecord = new HazardExamineRectificationReturnRecord();
            returnRecord.setReturnUserId(user.getUserId());
            returnRecord.setReturnRealName(user.getUname());
            returnRecord.setTenantId(hazardExamineRecordDto.getTenantId());
            returnRecord.setExamineId(hazardExamineRecordDto.getExamineId());
            returnRecord.setExamineRecordId(hazardExamineRecordDto.getExamineRecordId());
            returnRecord.setReturnReason(hazardExamineRecordDto.getReturnReason());
            returnRecord.setCreatedTime(new Date());
            hazardExamineRectificationReturnRecordService.createHazardExamineRectificationReturnRecord(returnRecord);
        }
    }

}
